<template>
  <div class="login_body" v-loading="isLoading">
    <div class="bg"/>
    <div class="box">
      <div class="title">课程管理系统-登录</div>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="账号"
          prop="accountName"
        >
          <el-input v-model=" form.accountName"/>
        </el-form-item>

        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="form.password" show-password/>
        </el-form-item>
        <el-form-item prop="remember">
          <el-checkbox v-model="remember">记住我</el-checkbox>
        </el-form-item>
        <el-form-item v-removeAriaHidden>
          <span>用户类型：</span>
          <el-radio v-model="selectRole" label="student">学生</el-radio>
          <el-radio v-model="selectRole" label="teacher">教师</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login_btn" @click="login">登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" class="login_btn" @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {loginAPI, parseToken} from '@/api/user';
import {checkStatusLogin, isEmpty} from "@/utils/checkString";
import {LOGIN_OK_KEY} from "@/constants/KEY";

export default {
  name: 'Login',
  data() {
    return {
      isLoading: false, // 加载状态标志
      remember: false,
      selectRole: 'student',
      form: {
        accountName: '',
        password: '',
        accountType: ''
      },
      rules: {
        accountName: [
          {required: true, message: '账号必须填写', trigger: 'blur'},
          {min: 3, max: 18, required: true, message: '账号必须3-18位', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码必须填写', trigger: 'blur'},
          {min: 3, max: 16, required: true, message: '密码必须3-16位', trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {
    const tempe = localStorage.getItem('form')
    if (tempe) {
      this.form.accountName = JSON.parse(tempe).accountName
      this.form.password = JSON.parse(tempe).password
      this.form.accountType = JSON.parse(tempe).accountType
      this.remember = true
    }
  },
  methods: {
    login() {
      // 将表单登录类型与selectRole关联
      if (isEmpty(this.selectRole)) {
        this.$message.error('用户类型为空')
        return
      }
      this.form.accountType = this.selectRole
      this.$refs.form.validate((ok) => {
        if (ok) {
          if (isEmpty(this.selectRole)) {
            this.$message.error('登录类型错误')
            return
          }
          loginAPI(this.form).then((res) => {
            this.isLoading = true; // 设置加载状态为true
            let checkRes = checkStatusLogin(res.data);
            if (!(checkRes === LOGIN_OK_KEY)) {
              this.isLoading = false; // 登录失败，关闭加载状态
              this.$message.error(checkRes + '，登录失败！');
              return;
            }
            // 登录成功->保存token、(记住我)form到本地存储
            this.$store.commit('user/setToken', res.data);
            if (this.remember) {
              this.form.accountType = this.selectRole;
              localStorage.setItem('form', JSON.stringify(this.form));
            }
            // 解析token,保存User信息到本地存储
            parseToken().then((res) => {
              localStorage.setItem('userInfo', JSON.stringify(res.data.info));
            }).catch(() => {
              this.isLoading = false; // 解析token出错，关闭加载状态
              this.$message.error('解析token出错！');
            });

            // 设置延迟跳转
            setTimeout(() => {
              this.isLoading = false; // 关闭加载状态
              this.$router.push(this.selectRole + '/home');
              this.$message.success('登录成功！');
            }, 500); // 延迟500毫秒（0.5秒）后跳转
          }).catch(() => {
            this.isLoading = false; // 服务器错误，关闭加载状态
            this.$message.error('服务超时！');
          });
        } else {
          this.$message.error('登录失败')
        }
      })
      // this.isLoading = false;
    },
    // 跳转到注册页面
    register() {
      if (isEmpty(this.selectRole)) {
        this.$message.error('注册类型为空')
        return
      }
      // 跳转到注册页
      this.$router.push('/register/' + (this.selectRole === 'teacher' ? 'teacher' : 'student'))
    }
  }
}

</script>

<style scoped lang="scss">
.login_body {
  display: flex;
}

.bg {
  width: 60vw;
  height: 100vh;
  background: url('~@/assets/login-bg.svg') no-repeat right top;
  background-size: contain;
}

.box {
  margin: 200px 10% 0;
  flex: 1;

  .title {
    padding-bottom: 76px;
    font-size: 26px;
    font-weight: 500;
    color: #1e2023;
  }

  //::v-deep{}是一种深度选择器，允许你穿透组件的作用域，对子组件的样式进行修改。CSS预处理器不识别::v-deep语法使用/deep/ 或 >>> 代替 ::v-deep
  >>> {
    .ant-form-item {
      display: flex;
      margin-bottom: 62px;
      flex-direction: column;
    }

    .ant-form-item-label label {
      font-size: 16px;
      color: #8b929d;
    }

    .ant-input,
    .ant-input-password {
      border-radius: 8px;
    }
  }
}

.login_btn {
  width: 100%;
}
</style>
